<template>
  <div id="labItemDict">
    <Breadcrumb content="仓库管理" />
    <div class="bodyContent">
      <Splitpanes>
        <Pane :size="50">
          <vxe-form :data="searchForm" class="searchform form-input-m">
            <vxe-form-item title="快速查询">
              <vxe-input v-model="searchForm.seachValue" placeholder="请输入" clearable @keyup="getStoreManageList" />
            </vxe-form-item>
            <vxe-form-item>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="getStoreManageList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addStoreManage"></vxe-button>
            </vxe-form-item>

          </vxe-form>
          <div class="tablecenter"  :style="{ height:'calc(100% - 90px)' }">
            <vxe-table ref="storeManageRef"  class="mytable-scrollbar" border="inner" height="auto" :data="storeManageList" :loading="showLoading" :expand-config="{ expandAll: true, reserve: true }" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" :keyboard-config="{
                isArrow: true,
                isTab: true,
                isEdit: true
              }" :tree-config="{
                expandAll: true,
                transform: true,
                rowField: 'id',
                parentField: 'parentId'
              }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" resizable show-overflow keep-source :reserve="true" @cell-click="curRowChangeEvent">
              <vxe-column field="storeCode" title="编码" tree-node></vxe-column>
              <vxe-column field="storeName" title="名称" ></vxe-column>
              <vxe-column field="storePyName" title="输入码"></vxe-column>
              <vxe-column field="isManage" title="管理库存">
                <template #default="{ row }">
                  <span>{{ row.isManage === 1 ? '是' : '否' }}</span>
                </template>
              </vxe-column>
<!--              <vxe-column field="deptNa" title="科室"></vxe-column>-->
              <vxe-column field="level" title="库房">
                <template #default="{ row }">
                  {{convertToChinese(row.level)}}
                </template>
              </vxe-column>
              <vxe-column title="操作" width="90" align="center" fixed="right">
                <template #default="{ row }">
                  <vxe-button v-show="row.level != 0" type="text" status="danger" icon="vxe-icon-delete" circle @click="deleteStoreManage(row)"></vxe-button>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>

        <Pane :size="50">
          <el-tabs type="border-card" v-model="activeTab">
            <el-tab-pane label="基础信息" name="first">
              <el-form ref="supplierFormRef" :model="supplierForm" :rules="supplierFormRule" label-width="100px" inline-message>
                <el-row>
                  <el-col :span="12">
                    <el-form-item prop="storeCode" label="仓库编码">
                      <el-input type="text" v-model="supplierForm.storeCode" placeholder="请输入仓库编码" clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item prop="storeName" label="仓库名称">
                      <el-input type="text" v-model="supplierForm.storeName" placeholder="请输入仓库名称" clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item prop="storePyName" label="输入码">
                      <el-input type="text" :disabled="true" v-model="supplierForm.storePyName" placeholder="请输入输入码" clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item prop="levelNa" label="库房">
                      <el-input :disabled="true" type="text"  v-model="supplierForm.levelNa" placeholder="请输入库房" clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item prop="isJoinStore" label="是否可调拨入库">
                      <el-switch v-model="supplierForm.isJoinStore" inline-prompt active-text="是" inactive-text="否" :active-value="1" :inactive-value="0"></el-switch>
                      <el-select v-show="supplierForm.isJoinStore ===1" multiple v-model="supplierForm.joinStoreData"  placeholder="请选择" size="small" clearable style="width:160px" teleported>
                        <el-option
                            v-for="item in joinStoreList"
                            :key="item.storeCode"
                            :label="item.storeName"
                            :value="item.storeCode"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item prop="isMoveStore" label="是否可调拨出库">
                      <el-switch v-model="supplierForm.isMoveStore" inline-prompt active-text="是" inactive-text="否" :active-value="1" :inactive-value="0"></el-switch>
                      <el-select v-show="supplierForm.isMoveStore ===1" multiple v-model="supplierForm.moveStoreData"  placeholder="请选择" size="small" clearable style="width:160px" teleported>
                        <el-option
                            v-for="item in moveStoreList"
                            :key="item.storeCode"
                            :label="item.storeName"
                            :value="item.storeCode"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item prop="isManage" label="是否管理库存">
                      <el-switch v-model="supplierForm.isManage" inline-prompt active-text="是" inactive-text="否" :active-value="1" :inactive-value="0"></el-switch>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item prop="deptNa" label="使用科室">
                      <VxePulldownSelectionWithNa
                          style="width: 100%"
                          :url="'/api/sys/findDepartmentListbyCurrentUserOrg'"
                          @confirmClick="SelectRowClick" :tableColumn="[
                { field: 'code', title: '编码' },
                { field: 'name', title: '名称' }
              ]" :aimKeys="[
                { aimKey: 'deptCode', rowKey: 'code' },
                { aimKey: 'deptNa', rowKey: 'name' }
              ]" :displayTexts="['deptNa']" :displayTextObj="supplierForm.deptNa ? supplierForm.deptNa : ''" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item prop="pricingSystem" label="计价体系">
                      <el-select v-model="supplierForm.pricingSystem" filterable placeholder="请选择">
                        <el-option v-for="supplierType in pricingSystemList" :key="supplierType.id" :label="supplierType.name" :value="supplierType.code"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item prop="outboundOrder" label="出库顺序">
                      <el-select v-model="supplierForm.outboundOrder" filterable placeholder="请选择">
                        <el-option v-for="supplierType in outboundOrderList" :key="supplierType.id" :label="supplierType.name" :value="supplierType.code"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item class="form-footer">
                      <template #default>
                        <el-button v-show="supplierForm.level != 0" type="primary" @click="saveSupplier('supplierFormRef')">保存</el-button>
                        <el-button v-show="supplierForm.level != 0" type="default" @click="resetForm()">重置</el-button>
                      </template>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="用户仓库" class="tab-content-wrapper" name="userTab">
              <UserMange ref="suerManageRef"/>
            </el-tab-pane>
            <el-tab-pane label="仪器仓库" class="tab-content-wrapper" name="intTab">
              <InstrMange ref="instrManageRef"/>
            </el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import Breadcrumb from '@/components/Breadcrumb.vue'; //面包屑
import { Splitpanes, Pane } from 'splitpanes';
import {getCurrentInstance, reactive, ref,onMounted} from "vue";
import {VxeMessage, VxeNotifyType} from "@/utils/CommonMessage";
import VxePulldownSelectionWithNa from '@/components/VxePulldownSelectionWithNa.vue';
import UserMange from './UserMange.vue';
import InstrMange from './InstrMange.vue';
import { AppStore } from '@/stores/store'; //'../../../stores/store';
import { isEmpty } from 'lodash';
let store = AppStore();

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
// 最左侧表单
let searchForm = reactive({
  seachValue: ''
});
let showLoading = ref(false); //表格加载状态
let saveLoading = ref(false); //表格加载状态
let storeManageList: any = reactive([]); //表格数据
let pricingSystemList: any = reactive([]); //表格数据
let outboundOrderList: any = reactive([]); //表格数据
let joinStoreList: any = reactive([]); //可调拨入库集合
let moveStoreList: any = reactive([]); //可调拨出库集合
let allotData: any = reactive({
  isJoinList:[],
  isMoveList:[]
}); //可入库的仓库集合
let suerManageRef: any = ref(null);
let instrManageRef: any = ref(null);
let storeManage: any = ref({});


let activeTab = ref('first');
// 右侧基本信息表单
let supplierForm = reactive({
  id: null,
  parentId: null,
  storeCode: '',
  storeName: '',
  storePyName: '',
  isManage: 0,
  isJoinStore: 0,
  joinStoreData: [],
  moveStoreData: [],
  isMoveStore: 0,
  deptCode: '',
  deptNa: '',
  level: '',
  levelNa: '',
  pricingSystem: '',
  outboundOrder: '',
  seq: 1,
  orgId: ''
});

let supplierFormRule = {

  storeCode: [
    {
      required: true,
      message: '请输入仓库编号',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ],
  storeName: [
    {
      required: true,
      message: '请输入仓库名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ]
};



// 方法定义区 =============
// 页面加载时更新组织机构列表(左侧)
onMounted(() => {
  getJoinOrMoveStore();
  getStoreManageList();
  getDictItemsList();
});

//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['pricingSystem','outboundOrder'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const planStatues = dictTreeTypeItems.data.find((item: any) => item.code === 'pricingSystem');
  pricingSystemList.push(...planStatues.detailDataList);
  const inspectionStatus = dictTreeTypeItems.data.find((item) => item.code === 'outboundOrder');
  outboundOrderList.push(...inspectionStatus.detailDataList);
}

// 获取仓库信息
function getStoreManageList() {
  storeManageList.length = 0;
  showLoading.value = true;
  const url = '/inv/storeManage/findStoreManageList';
  proxy.$http
      .get(url, { params: searchForm })
      .then((res: any) => {
        storeManageList.push(...res.data);
        const time=Date.now();
        proxy.$nextTick(() => {
          const $table = proxy.$refs.storeManageRef;
          if($table){
            $table.setAllRowExpand(true);
            $table.setAllTreeExpand(true);
          }
        })
        if (storeManageList.length ==0){
          suerManageRef.value.clearData();
          instrManageRef.value.clearData();
        }
        const kn = storeManageList.find((k) => k.id == storeManage.value.id);
        if (isEmpty(kn)) {
          curRowChangeEvent({ row: storeManageList[0] }); //默认选中第一条数据
        } else {
          curRowChangeEvent({ row: kn }); //默认选中第一条数据
        }
        showLoading.value = false;
      })
      .catch((err: any) => {
        proxy.$alert(err, '提示');
        showLoading.value = false;
      });
}

//获取可调拨入库出库数据
function getJoinOrMoveStore() {
  const url = '/inv/storeManage/getJoinOrMoveStore';
  proxy.$http
      //注意此处的数据条数
      .get(url)
      .then((res: any) => {
        Object.assign(allotData, res.data);
      })
      .catch((err: any) => {
      });
}
// 新建一级机构/子结构
async function addStoreManage(): Promise<void> {
  clearForm();
  if (!isEmpty(storeManage) && !isEmpty(storeManage.value.id)){
    supplierForm.level= storeManage.value.id != '' && storeManage.value.id != null ? storeManage.value.level+1 : 1;
    supplierForm.levelNa=convertToChinese(storeManage.value.level+1);
    supplierForm.parentId= storeManage.value.id != '' || storeManage.value.id != null ? storeManage.value.id : null;
  }else {
    storeManage.value = {};
  }
}
// 清空中间规则弹框表单
function clearForm() {
  supplierForm.id = null;
  supplierForm.parentId = null;
  supplierForm.storeCode = '';
  supplierForm.storeName = '';
  supplierForm.storePyName = '';
  supplierForm.isManage = 0;
  supplierForm.isJoinStore = 0;
  supplierForm.isMoveStore = 0;
  supplierForm.deptCode = '';
  supplierForm.deptNa = '';
  supplierForm.level = '';
  supplierForm.pricingSystem = '';
  supplierForm.outboundOrder = '';
  supplierForm.seq = storeManageList.length+1;
  supplierForm.orgId = '';
}
function resetForm() {
  supplierForm.storeCode = '';
  supplierForm.storeName = '';
  supplierForm.storePyName = '';
  supplierForm.isManage = 0;
  supplierForm.isJoinStore = 0;
  supplierForm.isMoveStore = 0;
  supplierForm.deptCode = '';
  supplierForm.deptNa = '';
  supplierForm.pricingSystem = '';
  supplierForm.outboundOrder = '';
  supplierForm.seq = storeManageList.length+1;
  supplierForm.orgId = '';
}

function saveSupplier(formName: any) {
  let $el = proxy.$refs[formName];
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
      const url = '/inv/storeManage/saveOrUpdateStoreManage';
      const supplier = {
        id: supplierForm.id,
        parentId: supplierForm.parentId,
        storeCode: supplierForm.storeCode,
        storeName: supplierForm.storeName,
        storePyName: supplierForm.storePyName,
        isManage: supplierForm.isManage,
        isJoinStore: supplierForm.isJoinStore,
        joinStoreData: supplierForm.joinStoreData.join(','),
        isMoveStore: supplierForm.isMoveStore,
        moveStoreData: supplierForm.moveStoreData.join(','),
        deptCode: supplierForm.deptCode,
        deptNa: supplierForm.deptNa,
        level: supplierForm.level,
        pricingSystem: supplierForm.pricingSystem,
        outboundOrder: supplierForm.outboundOrder,
        seq: supplierForm.seq,
        orgId: store.userInfo.orgId
      };
      proxy.$http
          .post(url, supplier)
          .then((res: any) => {
            VxeMessage('操作成功', VxeNotifyType.success);
            clearForm();
            storeManage.value.id = res.data.id;
            getStoreManageList();
          })
          .catch((err: any) => {
            VxeMessage('新增失败', VxeNotifyType.error);
          });
  });
}
// 删除机构
function deleteStoreManage(row: any) {
  let $table = proxy.$refs.storeManageRef;

  $table.setAllTreeExpand(true);
  $table.setAllRowExpand(true);
  proxy
      .$confirm('确定删除此设备？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        const url = '/inv/storeManage/deleteStoreManage';
        if (row.id) {
          proxy.$http.post(url, row).then((res: any) => {
            if (res.status.code === 400) {
              VxeMessage('删除失败', VxeNotifyType.error);
            } else {
              VxeMessage('删除成功', VxeNotifyType.success);
            }
            getStoreManageList();
            $table.setAllTreeExpand(true);
          });
        } else {
          if ($table) {
            await $table.remove(row);
            VxeMessage('删除成功', VxeNotifyType.success);
          }
        }
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
}

// 表格点击当前行
function curRowChangeEvent({ row }) {
  clearForm();
  joinStoreList.length=0;
  moveStoreList.length=0;
    for (const item of allotData.isJoinList) {
      if (item.id != row.id) {
        joinStoreList.push(item);
      }
    }
    for (const item of allotData.isMoveList) {
      if (item.id != row.id) {
        moveStoreList.push(item);
      }
    }
  proxy.$nextTick(() => {
    setSupplierForm(row);
    // 默认选中第一行
    (proxy.$refs.storeManageRef as any).setCurrentRow(row);
    suerManageRef.value.initPage(row);
    instrManageRef.value.initPage(row);
  })

}
/**下拉选中行事件 */
async function SelectRowClick(e) {
  e.aimKeys.forEach((r) => {
    supplierForm[r.aimKey] = e.row[r.rowKey];
  });
}
//处理中文层级
function convertToChinese(num) {
  const chineseNumbers = ["", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"];
  if (num >= 0 && num < chineseNumbers.length) {
    if (num == 0){
      return chineseNumbers[num];
    }else {
      return chineseNumbers[num]+'级库房';

    }
  }
  return "未知";
}
// 编辑当前行规则
function setSupplierForm(row: any) {
  supplierForm.id = row.id;
  supplierForm.storeCode = row.storeCode;
  supplierForm.storeName = row.storeName;
  supplierForm.storePyName = row.storePyName;
  supplierForm.isManage = row.isManage;
  supplierForm.isJoinStore = row.isJoinStore;
  supplierForm.joinStoreData = (!isEmpty(row.joinStoreData)?row.joinStoreData.split(','):[]);
  supplierForm.isMoveStore = row.isMoveStore;
  supplierForm.moveStoreData = (!isEmpty(row.moveStoreData)?row.moveStoreData.split(','):[]);
  supplierForm.deptCode = row.deptCode;
  supplierForm.deptNa = row.deptNa;
  supplierForm.level = row.level;
  supplierForm.levelNa=convertToChinese(row.level);
  supplierForm.pricingSystem = row.pricingSystem;
  supplierForm.outboundOrder = row.outboundOrder;
  supplierForm.seq = row.seq;
  supplierForm.orgId = row.orgId;
  storeManage.value=row;
}


</script>
<style lang="scss" scoped>
#labItemDict {
  width: 100%;
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    .splitpanes {
      background-color: $base-white;

      .el-tabs {
        height: 100%;

        :deep(.el-tabs__content) {
          height: calc(100% - 40px);
          padding: 0 10px;

          .el-tab-pane {
            height: 100%;
          }
          #pane-first {
            padding: 15px;
          }
        }
      }
    }

    .searchform {
      padding: 10px 0 0 10px;

      :deep(.vxe-form--item) {
        margin-right: 30px;
      }
    }

    .searchform .vxe-input {
      --el-input-width: 120px;
    }

    .searchform .vxe-select {
      --el-select-width: 120px;
    }

    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }
  }
}
</style>
